/*
 * DotProduct.h
 *
 *  Created on: Feb 3, 2010
 *      Author: Jamie LaPointe
 *
 *       Notes: Original code is in C and located at:
 *              https://computing.llnl.gov/tutorials/pthreads/#Pthread
 */

#ifndef THREADEDDOTPRODUCT_H_
#define THREADEDDOTPRODUCT_H_

#include <pthread.h>
#include <cstdlib>

namespace MutexExample
{

struct DotData
{
   int vectorLength;
   double * a;
   double * b;
   double sum;
};

struct DotArg
{
   int index;
   DotData * dotData;
   pthread_mutex_t * mutexSum;
};

void * computeDotProduct(void * arg);

class ThreadedDotProduct
{
private:
   const int numThreads_;
   const int vectorLength_;
   pthread_mutex_t mutexSum_;
   pthread_t * callThread_;
   DotData dotData_;
   DotArg dotArg_;

public:
   ThreadedDotProduct() :
      numThreads_(4),
      vectorLength_(100)
   {
      callThread_ = (pthread_t *)malloc(numThreads_ * sizeof(pthread_t));
   }

   ThreadedDotProduct(int numThreads, int vectorLength) :
      numThreads_(numThreads),
      vectorLength_(vectorLength)
   {
      callThread_ = (pthread_t *)malloc(numThreads_ * sizeof(pthread_t));
   }

   ~ThreadedDotProduct()
   {
      //
      // cleanup after yourself.
      //
      pthread_mutex_destroy(&mutexSum_);
      free(callThread_);
      callThread_ = 0;
      pthread_exit(0);
   }

   double run();
};

}

#endif /* THREADEDDOTPRODUCT_H_ */
